#
# messkit.threaded_stream
#
# Copyright 2006-2008 Helsinki Institute for Information Technology (HIIT)
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Stream implementation based on blocking send/recv

Each stream instance has two threads, one to handle inbound traffic,
and the other to handle outbound traffic.  This actually works okay.
"""

import socket
import os

from messkit.async import Thread, ThreadExit
from messkit.stream import Stream as _Stream
from messkit.stream import StreamServer as _StreamServer
from messkit.stream import StreamManager as _StreamManager

__all__ = ['Stream', 'StreamServer', 'StreamManager']

class Stream(_Stream):
    def _init(self, arg):
        if isinstance(arg, tuple):
            self.socket = socket.socket(*arg)
        elif isinstance(arg, socket.SocketType):
            self.socket = arg
        else:
            raise TypeError

        self.socket.settimeout(None)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        self.inbound_thread = Thread(name='inbound_thread')
        self.outbound_thread = Thread(name='outbound_thread')

    def _close(self, flush, cb):
        # XXX Support flush == False.  Currently this flag is ignored.
        self.outbound_thread.async(self.__close, cb)
        self.outbound_thread.terminate()
        self.inbound_thread.terminate()

    def __close(self, cb=None):
        self.socket.close()
        self.issue_callback(cb)

    def _connect(self, address, cb):
        self.outbound_thread.async(self.__connect, address, cb)

    def __connect(self, address, cb):
        errno = self.socket.connect_ex(address)
        if errno == 0:
            error = None
        else:
            error = socket.error(errno, os.strerror(errno))
            self.error = error

        self.issue_callback(cb, error)

    def _flush(self, buf, cb=None):
        self.outbound_thread.async(self.__flush, buf, cb)

    def __flush(self, buf, cb):
        while buf.size and not self.error:
            s = buf.read(self.send_size)
            try:
                self.socket.sendall(s)
                self.bytes_out += len(s)
            except socket.error, e:
                self._signal_error(e)
                return

        self.issue_callback(cb)

    def _fill(self, buf, size, cb):
        self.inbound_thread.async(self.__fill, buf, size, cb)

    def __fill(self, buf, size, cb):
        n = 0
        while n < size and not self.eof_seen:
            try:
                s = self.socket.recv(self.recv_size)
            except socket.error, e:
                self._signal_error(e)
                return

            if not s:
                self.eof_seen = True
            else:
                self.bytes_in += len(s)
                buf.append(s)
                n += len(s)

        self.issue_callback(cb, n)

class StreamServer(_StreamServer):
    def _init(self, socket_params):
        self.socket_params = socket_params
        self.address = None

        self.socket = socket.socket(*socket_params)
        self.socket.settimeout(None)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.thread = Thread(name='server_thread')

    def _close(self, cb):
        self.thread.async(self.__close, cb)
        self.thread.terminate()
        if self.address is not None:
            # Cause any blocked accept() to fall through.
            sock = socket.socket(*self.socket_params)
            try:
                sock.connect(self.address)
                sock.close()
            except Exception:
                pass

    def __close(self, cb):
        self.socket.close()
        self.issue_callback(cb)

    def _listen(self, address):
        self.address = address
        self.socket.bind(address)
        self.socket.listen(5)

    def _accept(self, cb):
        self.thread.async(self.__accept, cb)

    def __accept(self, cb):
        if not self.closed:
            conn, addr = self.socket.accept()
            if self.closed:
                conn.close()
            else:
                self.issue_callback(cb, conn, addr)

class StreamManager(_StreamManager):
    def _create_stream(self, *args):
        return Stream(self, *args)

    def _create_server(self, socket_params):
        return StreamServer(self, socket_params)
